package cn.piggy.type;

import cn.piggy.config.ConfigParam;
import cn.piggy.model.answers.AiRequestBody;
import cn.piggy.util.TokenStorageUtil;
import okhttp3.Request;

import java.io.IOException;

public class AnswerType extends AiTypeBase {
    @Override
    public String getHost(Object object) throws IOException {
        if(object instanceof AiRequestBody){
            return ConfigParam.getConfigParam().getApiHost();
        }
        throw new RuntimeException("not find request url");
    }

    @Override
    public String queryToken() throws IOException {
        String token = TokenStorageUtil.tokens.get(this.getClass().getSimpleName() + "#TOKEN");
        if(token==null){
            synchronized (AnswerType.class){
                token = TokenStorageUtil.tokens.get(this.getClass().getSimpleName() + "#TOKEN");
                if(token==null){
                    String clientId = ConfigParam.getConfigParam().getClientId();
                    String clientSecret = ConfigParam.getConfigParam().getClientSecret();
                    String authHost = ConfigParam.getConfigParam().getAuthHost();
                    String url = authHost+"?grant_type=client_credentials&client_id="+clientId+"&client_secret="+clientSecret;
                    Request request = new Request.Builder().url(url).build();
                    token = requestToken(request);
                    TokenStorageUtil.tokens.put(this.getClass().getSimpleName() + "#TOKEN", token);
                }
            }
        }
        return token;
    }
}
